package com.JL.engine.util;

import com.JL.engine.View.ImageView;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AssetsLoader {

    private static final String IMAGE_PATH = "images";

    private static File rootPath;

    /*
    * 初始化资源加载器*/
    public static void initAssetsLoader(File rootPath) {
        AssetsLoader.rootPath = rootPath;
    }


    /*
     * 初始化资源加载器*/
    public static void initAssetsLoader(String rootPath) {
        AssetsLoader.rootPath = new File(rootPath);
    }

    /*
     * 初始化资源加载器是否已经初始化*/
    private static void checkInit() {
        if (rootPath == null) {
            throw new RuntimeException("AssetsLoader is not innit");
        }
    }

    /*
     * 获取图片文件
     * */
    private static File getImageFile(String imageName) throws FileNotFoundException {
        File file = new File(rootPath,IMAGE_PATH + File.separator + imageName);
        if (!file.exists()){
            throw new FileNotFoundException("image file not found:"+file.getAbsolutePath());
        }
        return file;
    }

    /*
    * 加载图片视图
    * */
    public static ImageView loadImage(String imageName, int x, int y, int width, int height){
        ImageView view = loadImage(imageName);
        return view.subImageView(x,y,width,height);
    }

    /*
     * 加载图片视图集合
     * */
    public static List<ImageView> loadImages(String imageNameFormat,int count,int start,int step){
        List<ImageView> views = new ArrayList<>();
        for (int i = 0,j=start; i < count; i++,j+=step) {
            views.add(loadImage(String.format(imageNameFormat,j)));
        }
        return views;
    }

    /*
     * 加载图片视图集合
     * */
    public static List<ImageView> loadImages(String imageName, List<Rectangle> rectangles) {
        List<ImageView> views = new ArrayList<>();
        ImageView imageView = loadImage(imageName);
        for (Rectangle rectangle : rectangles) {
            views.add(imageView.subImageView(rectangle));
        }
        return views;
    }


    /*
     * 加载图片视图
     * */
    public static ImageView loadImage(String imageName){

        try {
            checkInit();
            BufferedImage image = ImageIO.read(getImageFile(imageName));
            return new ImageView(image);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
